package com.atguigu.tingshu.order.strategy.impl;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.service.OrderDerateService;
import com.atguigu.tingshu.order.service.OrderDetailService;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.order.strategy.SaveOrderStrategy;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Author  王东剑
 * Created on 23/6/2024 PM1:58
 * Package_name com.atguigu.tingshu.order.strategy.impl
 * Description
 */
@Service
@Slf4j
public class WeiXinSaveOrderStrategy implements SaveOrderStrategy {
	@Autowired
	private OrderInfoService orderInfoService;
	@Autowired
	private OrderDetailService orderDetailService;
	@Autowired
	private OrderDerateService orderDerateService;
	@Autowired
	private RedissonClient redissonClient;

	@Override
	public OrderInfoVo saveOrder(OrderInfoVo orderInfoVo) {
		System.out.println("WeiXinSaveOrderStrategy.saveOrder");
		/*
		 * 1.保存订单信息
		 * 2.保存订单明细
		 * 3.保存订单折扣
		 */
		this.saveOrderInfoAndOrderDetailAndOrderDerate(orderInfoVo,
				orderInfoService,
				orderDetailService,
				orderDerateService);
		// 将未支付的订单发送至延迟队列
		String orderNo = orderInfoVo.getTradeNo();

		return orderInfoVo;
	}

	public void addDelayQueue(String orderNo) {
		RBlockingDeque<String> rBlockingDeque = redissonClient.getBlockingDeque(RedisConstant.QUEUE_ORDER_CANCEL);
		RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(rBlockingDeque);
		// TODO: 延时时间记得改回 RedisConstant.DELAY_TIME
		delayedQueue.offer(orderNo, RedisConstant.DELAY_TIME, TimeUnit.SECONDS);
		log.info("添加延时队列成功 ，延迟时间：{}，订单id：{}", RedisConstant.DELAY_TIME, orderNo);
	}


	@Override
	public String getPayWay() {
		return SystemConstant.ORDER_PAY_WAY_WEIXIN;
	}

	@Override
	public void saveOrderAfterProcess(String orderNo) {
		this.addDelayQueue(orderNo);
	}
}
